﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using WorkFlowSystem.DataBase;
using System.Drawing;
using System.Data.SqlClient;
using System.Windows.Forms;
using WorkFlowSystem.Common;
using WorkFlowSystem.Business;

namespace WorkFlowSystem
{
    public partial class UserStandardUi : Form
    {
        public UserStandardUi()
        {
            InitializeComponent();
            m_modify_mode = false;
            m_us_info = new UserStandardInfo();
        }

        private void UserStandardUi_Load(object sender, EventArgs e)
        {
            if (m_modify_mode)
            {
                init_modify_user_standard();
            }
            else
            {
                init_add_user_standard();
            }
        }

        private void common_init()
        {
            comboBoxEx1.Items.Clear();
            int year = DateTime.Now.Year;
            for (int i = 0; i < 5; i++)
            {
                comboBoxEx1.Items.Add(year);
                year++;
            }
            comboBoxEx1.SelectedIndex = 0;

            comboBoxEx2.Items.Clear();
            comboBoxEx2.Items.Add("-");
            for (int i = 1; i < 5; i++)
            {
                comboBoxEx2.Items.Add(i);
            }
            comboBoxEx2.SelectedIndex = 0;

            comboBoxEx3.Items.Clear();
            comboBoxEx3.Items.Add("-");
            for (int i = 1; i < 13; i++)
            {
                comboBoxEx3.Items.Add(i);
            }
            comboBoxEx3.SelectedIndex = 0;
        }

        private void init_add_user_standard()
        {
            common_init();
            buttonX5.Enabled = false;
        }

        private void init_modify_user_standard()
        {
            common_init();
            if (load_user_standard() < 0) {
                MessageBox.Show("获取标准关联信息失败");
                this.Close();
                return;
            }

            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return;
            }
            string sql = "select u_name from user_info where uid=@uid";
            List<SqlParameter> para_list = new List<SqlParameter>();
            para_list.Add(new SqlParameter("@uid", m_us_info.uid));
            DataTable dt = new DataTable();
            if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
            {
                MessageBox.Show("获取员工失败");
                db_op.CloseDB();
                this.Close();
                return;
            }
            string u_name = dt.Rows[0]["u_name"].ToString();

            sql = "select s_name from standard where sid=@sid";
            para_list.Clear();
            para_list.Add(new SqlParameter("@sid", m_us_info.sid));
            dt.Clear();
            if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
            {
                MessageBox.Show("获取标准失败");
                db_op.CloseDB();
                this.Close();
                return;
            }
            db_op.CloseDB();
            string s_name = dt.Rows[0]["s_name"].ToString();

            listBox1.Items.Add(u_name);
            listBox2.Items.Add(s_name);

            comboBoxEx1.Text = m_us_info.start_date.Year.ToString();
            dateTimeInput1.Value = m_us_info.start_date;
            dateTimeInput2.Value = m_us_info.end_date;

            if (m_us_info.type == "D")
            {
                radioButton4.Select();
            }
            else if (m_us_info.type == "M")
            {
                radioButton3.Select();
            }
            else if (m_us_info.type == "Q")
            {
                radioButton2.Select();
            }
            else if (m_us_info.type == "Y")
            {
                radioButton1.Select();
            }
            else
            {
                Logger.WriteLogError("invalid us_type");
                MessageBox.Show("标准区间不正确");
                this.Close();
                return;
            }

            listBox1.Enabled = false;
            listBox2.Enabled = false;

            buttonX1.Enabled = false;
            buttonX2.Enabled = false;
            buttonX4.Enabled = false;

            comboBoxEx1.Enabled = false;
            comboBoxEx2.Enabled = false;
            comboBoxEx3.Enabled = false;

            radioButton1.Enabled = false;
            radioButton2.Enabled = false;
            radioButton3.Enabled = false;
            radioButton4.Enabled = false;

            dateTimeInput1.Enabled = false;
            dateTimeInput2.Enabled = false;
        }

        private int load_user_standard()
        {
            Logger.WriteLog("enter load_user_standard");
            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return -1;
            }

            string sql = "select * from user_standard where us_uid=@uid and us_sid=@sid and us_start_date=@start_date and us_end_date=@end_date";
            DataTable dt = new DataTable();
            List<SqlParameter> para_list = new List<SqlParameter>();
            para_list.Add(new SqlParameter("@uid", m_us_info.uid));
            para_list.Add(new SqlParameter("@sid", m_us_info.sid));
            para_list.Add(new SqlParameter("@start_date", m_us_info.start_date));
            para_list.Add(new SqlParameter("@end_date", m_us_info.end_date));
            if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
            {
                Logger.WriteLog("get user_standard info fail");
                db_op.CloseDB();
                return -1;
            }
            m_us_info.type = dt.Rows[0]["us_type"].ToString();
            db_op.CloseDB();
            return 0;
        }

        /// <summary>
        /// 查看同一标准是否在同一区间重复关联相同员工
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public int is_multi_standard(string sid, string uid)
        {
            Logger.WriteLog("Check if selected standard is already chosen");
            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return -1;
            }
            string sql = "select * from user_standard where us_sid=@sid and us_uid=@uid";
            List<SqlParameter> para_list = new List<SqlParameter>();
            para_list.Add(new SqlParameter("@sid", sid));
            para_list.Add(new SqlParameter("@uid", uid));
            DataTable dt = new DataTable();
            if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
            {
                MessageBox.Show("获取用户关联信息失败");
                db_op.CloseDB();
                return -1;
            }
            db_op.CloseDB();

            if (dt.Rows.Count > 0) {
                for (int i = 0; i < dt.Rows.Count; i++) {
                    DateTime dt_start_date = DateTime.Parse(dt.Rows[i]["us_start_date"].ToString());
                    DateTime dt_end_date = DateTime.Parse(dt.Rows[i]["us_end_date"].ToString());
                    DateTime start_date = m_us_info.start_date;
                    DateTime end_date = m_us_info.end_date;

                    if ((DateTime.Compare(dt_start_date, start_date) > 0 && DateTime.Compare(dt_start_date, end_date) < 0) ||
                        (DateTime.Compare(dt_end_date, start_date) > 0 && DateTime.Compare(dt_end_date, end_date) < 0) ||
                        (DateTime.Compare(dt_start_date, start_date) < 0 && DateTime.Compare(dt_end_date, end_date) > 0))
                    {
                        Logger.WriteLog("multi standard in the same duration");
                        return -1;
                    }
                }
            }
            return 0;
        }

        /// <summary>
        /// 设置初始化模式
        /// </summary>
        /// <param name="modify_mode"></param>
        /// <param name="standard_id"></param>
        public void SetMode(bool modify_mode, string us_uid, string us_sid, string us_start_date, string us_end_date)
        {
            m_modify_mode = modify_mode;
            if (m_modify_mode)
            {
                m_us_info.uid = us_uid;
                m_us_info.sid = us_sid;
                m_us_info.start_date = DateTime.Parse(us_start_date);
                m_us_info.end_date = DateTime.Parse(us_end_date);
            }
        }

        /// <summary>
        /// 显示员工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX1_Click(object sender, EventArgs e)
        {
            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return;
            }
            string sql = "select uid, u_name from user_info where u_did=(select did from department where d_uid=@uid)";
            List<SqlParameter> para_list = new List<SqlParameter>();
            para_list.Add(new SqlParameter("@uid", CurrentUser.user_id));
            DataTable dt = new DataTable();
            if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
            {
                MessageBox.Show("获取员工失败");
                db_op.CloseDB();
                return;
            }
            db_op.CloseDB();

            listBox1.DataSource = dt;
            listBox1.ValueMember = "uid";
            listBox1.DisplayMember = "u_name";
            
        }

        /// <summary>
        /// 显示标准
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX2_Click(object sender, EventArgs e)
        {
            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return;
            }
            string sql = "select distinct sid, s_name from standard where s_insert_uid=@uid";
            List<SqlParameter> para_list = new List<SqlParameter>();
            para_list.Add(new SqlParameter("@uid", CurrentUser.user_id));
            DataTable dt = new DataTable();
            if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
            {
                MessageBox.Show("获取标准失败");
                db_op.CloseDB();
                return;
            }
            db_op.CloseDB();

            listBox2.DataSource = dt;
            listBox2.ValueMember = "sid";
            listBox2.DisplayMember = "s_name";
        }

        /// <summary>
        /// 预览标准
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX3_Click(object sender, EventArgs e)
        {
            WorkInfoInput wii = new WorkInfoInput(false, true, m_us_info.uid, m_us_info.sid, m_us_info.start_date.ToString(), m_us_info.end_date.ToString(), "未填写");
            if (wii.dataExistFlag == true)
            {
                wii.ShowDialog();
            }
        }

        /// <summary>
        /// 制定关联
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX4_Click(object sender, EventArgs e)
        {
            if (m_us_info.type == "D")
            {
                m_us_info.start_date = dateTimeInput1.Value;
                m_us_info.end_date = dateTimeInput2.Value;

                int year = int.Parse(comboBoxEx1.SelectedItem.ToString());
                if (year != dateTimeInput1.Value.Year || year != dateTimeInput2.Value.Year)
                {
                    Logger.WriteLogError("wrong year value");
                    MessageBox.Show("日期和所选择的年份不匹配");
                    return;
                }
            }

            if (listBox1.SelectedItems.Count == 0 || listBox2.SelectedItems.Count == 0) {
                MessageBox.Show("请选择员工和标准");
                return;
            }

            string uid = listBox1.SelectedValue.ToString();
            string sid = listBox2.SelectedValue.ToString();
            if (is_multi_standard(sid, uid) < 0)
            {
                MessageBox.Show("该关联在该区间已存在，请选择其他标准或更改区间");
                return;
            }

            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return;
            }
            string sql = "insert into user_standard(us_uid, us_sid, us_start_date, us_end_date, us_type, us_insert_uid, us_insert_date, us_update_uid, us_update_date) " +
                        "values(@uid, @sid, @start_date, @end_date, @type, @insert_uid, @insert_date, @update_uid, @update_date);\n";
            sql += "update standard set s_relate_flag=1 where sid=@sid;\n";
            sql += "insert into work_info(w_uid, w_sid, w_start_date, w_end_date, w_date_name, w_status, w_tab_1, w_tab_2, w_tab_3, w_tab_4, w_tab_5, w_tab_6, w_tab_7, w_tab_8, w_tab_9, w_tab_10, w_notes, w_manager_notes, w_insert_uid, w_insert_time, w_update_uid, w_update_time) " +
                "values(@uid, @sid, @start_date, @end_date, @date_name, @status, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null, null, @insert_uid, @insert_date, @update_uid, @update_date)";
            
            DateTime insert_date = DateTime.Now;
            string date_name = "";
            if (m_us_info.type == "D") {
                date_name = "D";
            }
            else if (m_us_info.type == "M") {
                date_name = m_us_info.start_date.Year + "年" + m_us_info.start_date.Month + "月";
            }
            else if (m_us_info.type == "Q") {
                date_name = m_us_info.start_date.Year + "年第" + (m_us_info.start_date.Month / 4 + 1) + "季度";
            }
            else if (m_us_info.type == "Y")
            {
                date_name = m_us_info.start_date.Year + "年";
            }
            else {
                MessageBox.Show("请选择区间类型");
                Logger.WriteLogError("invalid us_type");
                return;
            }

            List<SqlParameter> para_list = new List<SqlParameter>();
            foreach (DataRowView dr in listBox1.SelectedItems)
            {
                string temp_uid = dr["uid"].ToString();
                para_list.Clear();
                para_list.Add(new SqlParameter("@uid", temp_uid));
                para_list.Add(new SqlParameter("@sid", sid));
                para_list.Add(new SqlParameter("@start_date", m_us_info.start_date.ToString()));
                para_list.Add(new SqlParameter("@end_date", m_us_info.end_date.ToString()));
                para_list.Add(new SqlParameter("@type", m_us_info.type));
                para_list.Add(new SqlParameter("@date_name", date_name));
                para_list.Add(new SqlParameter("@status", "未填写"));
                para_list.Add(new SqlParameter("@insert_uid", CurrentUser.user_id));
                para_list.Add(new SqlParameter("@insert_date", insert_date.ToString()));
                para_list.Add(new SqlParameter("@update_uid", CurrentUser.user_id));
                para_list.Add(new SqlParameter("@update_date", insert_date.ToString()));
                Logger.WriteSqlLog(sql, para_list);
                if (db_op.ExecuteNonQuery(sql, para_list, true) < 0)
                {
                    MessageBox.Show("关联标准失败");
                    db_op.CloseDB();
                    return;
                }
            }
            db_op.CloseDB();

            if (OnChange != null)
                OnChange(sender, e);
            this.Close();
        }

        /// <summary>
        /// 删除关联
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX5_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定删除?", "删除关联", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                DBOperator db_op = new DBOperator();
                if (db_op.ConnectDB() < 0)
                {
                    MessageBox.Show("无法连接服务器，请检查网络连接");
                    return;
                }
                List<SqlParameter> para_list = new List<SqlParameter>();
                string sql = "delete from user_standard where us_uid=@uid and us_sid=@sid and us_start_date=@start_date and us_end_date=@end_date;\n";
                sql += "delete from work_info where w_uid=@uid and w_sid=@sid and w_start_date=@start_date and w_end_date=@end_date;\n";
                sql += "declare @rowcnt int;\n";
                sql += "select @rowcnt=COUNT(*) from erp_database.dbo.user_standard where us_sid=10000;\n";
                sql += "if @rowcnt = 0 update standard set s_relate_flag=0 where sid=@sid";
                para_list.Add(new SqlParameter("@uid", m_us_info.uid));
                para_list.Add(new SqlParameter("@sid", m_us_info.sid));
                para_list.Add(new SqlParameter("@start_date", m_us_info.start_date));
                para_list.Add(new SqlParameter("@end_date", m_us_info.end_date));

                if (db_op.ExecuteNonQuery(sql, para_list, true) < 0)
                {
                    MessageBox.Show("删除关联失败");
                }
                db_op.CloseDB();
                if (OnChange != null)
                    OnChange(sender, e);
                this.Close();
            }
        }

        /// <summary>
        /// 选择年份
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxEx1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int year = int.Parse(comboBoxEx1.SelectedItem.ToString());

            dateTimeInput1.Value = new DateTime(year, dateTimeInput1.Value.Month, dateTimeInput1.Value.Day);
            dateTimeInput2.Value = new DateTime(year, dateTimeInput2.Value.Month, dateTimeInput2.Value.Day);
        }

        /// <summary>
        /// 年
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            int year = int.Parse(comboBoxEx1.SelectedItem.ToString());

            comboBoxEx2.SelectedIndex = 0;
            comboBoxEx2.Enabled = false;

            comboBoxEx3.SelectedIndex = 0;
            comboBoxEx3.Enabled = false;

            dateTimeInput1.Value = new DateTime(year, 1, 1);
            dateTimeInput2.Value = new DateTime(year, 12, 31);

            dateTimeInput1.Enabled = false;
            dateTimeInput2.Enabled = false;

            m_us_info.start_date = dateTimeInput1.Value;
            m_us_info.end_date = dateTimeInput2.Value;
            m_us_info.type = "Y";

        }

        /// <summary>
        /// 季度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            comboBoxEx2.SelectedIndex = 0;
            comboBoxEx2.Enabled = true;

            comboBoxEx3.SelectedIndex = 0;
            comboBoxEx3.Enabled = false;

            dateTimeInput1.Enabled = false;
            dateTimeInput2.Enabled = false;

            m_us_info.type = "Q";
        }

        /// <summary>
        /// 月
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            comboBoxEx2.SelectedIndex = 0;
            comboBoxEx2.Enabled = false;

            comboBoxEx3.SelectedIndex = 0;
            comboBoxEx3.Enabled = true;

            dateTimeInput1.Enabled = false;
            dateTimeInput2.Enabled = false;

            m_us_info.type = "M";
        }

        /// <summary>
        /// 日
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            comboBoxEx2.SelectedIndex = 0;
            comboBoxEx2.Enabled = false;

            comboBoxEx3.SelectedIndex = 0;
            comboBoxEx3.Enabled = false;

            dateTimeInput1.Enabled = true;
            dateTimeInput2.Enabled = true;

            m_us_info.type = "D";
        }

        /// <summary>
        /// 季度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxEx2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxEx2.Text == "-")
                return;
            int year = int.Parse(comboBoxEx1.Text);
            int season = int.Parse(comboBoxEx2.Text);
            if (season == 1) {
                dateTimeInput1.Value = new DateTime(year, 1, 1);
                dateTimeInput2.Value = new DateTime(year, 3, 31);
            }
            else if (season == 2) {
                dateTimeInput1.Value = new DateTime(year, 4, 1);
                dateTimeInput2.Value = new DateTime(year, 6, 30);
            }
            else if (season == 3) {
                dateTimeInput1.Value = new DateTime(year, 7, 1);
                dateTimeInput2.Value = new DateTime(year, 9, 30);
            }
            else if (season == 4) {
                dateTimeInput1.Value = new DateTime(year, 10, 1);
                dateTimeInput2.Value = new DateTime(year, 12, 31);
            }

            m_us_info.start_date = dateTimeInput1.Value;
            m_us_info.end_date = dateTimeInput2.Value;
        }

        /// <summary>
        /// 月
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxEx3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxEx3.Text == "-")
                return;
            int year = int.Parse(comboBoxEx1.Text);
            int month = int.Parse(comboBoxEx3.Text);

            if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
            {
                dateTimeInput1.Value = new DateTime(year, month, 1);
                dateTimeInput2.Value = new DateTime(year, month, 31);
            }
            else if (month == 4 || month == 6 || month == 9 || month == 11)
            {
                dateTimeInput1.Value = new DateTime(year, month, 1);
                dateTimeInput2.Value = new DateTime(year, month, 30);
            }
            else if (month == 2)
            {
                dateTimeInput1.Value = new DateTime(year, month, 1);
                if(DateTime.IsLeapYear(year))
                    dateTimeInput2.Value = new DateTime(year, month, 29);
                else
                    dateTimeInput2.Value = new DateTime(year, month, 28);
            }

            m_us_info.start_date = dateTimeInput1.Value;
            m_us_info.end_date = dateTimeInput2.Value;
        }

        private bool m_modify_mode;
        private UserStandardInfo m_us_info;
        public delegate void UserStandardChange(object sender, EventArgs e);
        public event UserStandardChange OnChange;

        
        
    }

    class UserStandardInfo
    {
        public UserStandardInfo()
        {
            uid = "";
            sid = "";
            type = "";
        }

        public string uid;
        public string sid;
        public DateTime start_date;
        public DateTime end_date;
        public string type;
    }
}
